<template>
	<view class="container">
		<view class="selected-all">
			<view class="drop-down-box" @click="btnShowHideClick()">
				<text class="dropdown-content">{{choiceContent||"选择配送方式"}}</text>
				<image class="dropdown-icon" :class="{select:isShowChoice}" src="/static/supermarket/icon_arrow.png" mode="widthFix"></image>
			</view>
			<!-- 弹框内容 -->
			<view class="dialog-view" v-if="isShowChoice">
				<text class="dialog-title" v-for="(item ,index) in choiceList" :key="index" @click="btnChoiceClick(index)">{{item.choiceItemContent}}</text>
			</view>
		</view>
		<view class="store-list">
			<view class="title">{{storeData.name}}</view>
			<view class="column" v-for="(item,index) in shoppCart" :key="index">
				<image class="left" :src="adminImgPath+item.image" mode="aspectFill"></image>
				<view class="center">
					<view class="name">{{item.name}}</view>
					<view class="num">X{{item.number}}</view>
				</view>
				<view class="right"><text>￥</text>{{item.total}}</view>
			</view>
			<view class="price-total">
				<view class="tag">价格合计</view>
				<view class="price"><text>￥</text>{{totalPrice}}</view>
			</view>
		</view>
		<view class="remarks">
			<view class="title">备注信息</view>
			<textarea v-model="remarks" placeholder="请输入备注信息" placeholder-style="fontSize: 22rpx" />
		</view>
		<view class="btn-box">
			<view class="btn-box-left">
				<view class="priceBox">
					<view class="hx-color-white"><text>￥</text>{{totalPrice}}</view>
				</view>
			</view>
			<view class="btn-box-right" @click="reserveMessage()">
				<view class="jiesuan">立即支付</view>
			</view>
		</view>
	</view>
</template>

<script>
	import ikz from '@/pages/Common/tools.js';
	var app = getApp();
	import Vue from 'vue'
	export default {
		components: {

		},
		data() {
			return {
				id: 0,
				scrollData: {},
				//购物车缓存 Storage 名称  
				shoppingCartStorageName: 'shopping_cart',
				//门店信息  
				storeData: {},
				//购物车
				shoppCart: [],
				//头部选项卡 参数为 0不显示选项卡,1,2
				tabIndex: 1,
				//结算价
				totalPrice: 0,
				//已优惠价 
				totalYhPrice: 0,
				//商品数量
				totalNumber: 0,
				remark: "",
				adminImgPath: app.globalData.adminImgPath,
				remarks: '',
				isShowChoice: false,
				choiceIndex: 0,
				choiceList: [
					{
						choiceItemContent: "到店自取",
						value: 1
					},
					{
						choiceItemContent: "校园跑腿",
						value: 2
					}
				],
				choiceContent: "",
				orderId: 0,
				orderNo: 0
			}
		},
		onLoad(option) {
			if (option.id) {
				this.id = option.id
				let totalPrice = 0
				let totalNumber = 0
				let totalOldPrice = 0
				let carts = uni.getStorageSync(this.shoppingCartStorageName) || []
				if (carts) {
					//根据缓存数据 获取购物车中属于本商店的商品
					for (let i in carts) {
						if (carts[i].store_id == option.id) {
							this.shoppCart = carts[i].shopping_cart;
							this.storeData = carts[i]
							break;
						}
					}
				}
				let cj = 0
				let op = 0
				let p = 0
				let num = 0
				//计算总商品数量和总价
				for (var i in this.shoppCart) {
					this.shoppCart[i].total = Number(this.shoppCart[i].total).toFixed(2)
					p = Number(this.shoppCart[i].price);
					op = Number(this.shoppCart[i].oldprice);
					num = Number(this.shoppCart[i].number)
					totalNumber += num
					totalPrice += p * num
					if (op > p) {
						cj += (op - p) * num
					}
				}
				this.totalPrice = Number(totalPrice).toFixed(2)
				this.totalYhPrice = cj
				this.templateId((res)=>{
				});
			}
		},
		methods: {
			//获取模板参数
			templateId(fn){
			  var path = '/xyb/wechat_mini_push/template_id_list';
			  var data = {}
			  ikz.post(path,data,(res)=>{
			    if(res.data.code){
			      this.template_id = res.data.data;
						console.log("template_id的值",this.template_id);
			    }else{
			      uni.showModal({
			        title: '提示',
			        content: res.data.msg,
			        showCancel: false,
			        success: function(res) {}
			      });
			    }
			    fn();
			  })
			},
			// 选择 
			btnChoiceClick(index) {
				this.isShowChoice = false
				this.choiceContent = this.choiceList[index].choiceItemContent
				this.choiceIndex = this.choiceList[index].value
			},
			// 显示与隐藏选择内容
			btnShowHideClick() {
				if (this.isShowChoice) {
					this.isShowChoice = false
				} else {
					this.isShowChoice = true
				}
			},
			// 订阅消息
			reserveMessage() {
				var temp_id = [
				  this.template_id.receive_order_success,
				]
				//订阅消息
				var that = this;
				uni.requestSubscribeMessage({
				  tmplIds: temp_id,
				  success(res) {
				      that.createOrder();
				  },
				  fail(res) {
				    that.up_status == 2;
				    if(res.errCode == 20004){
				      uni.showModal({
				        title: '提示',
				        content: '请前往设置打开接受通知',
				        confirmText: '确定',
				        success(res) {
							that.createOrder();
						}
				      })
					
				    }else{
				      uni.showModal({
				        title: '提示',
				        content: '未订阅消息，无法接收到订单通知',
				        confirmText: '确定',
				        success(res) {
							 that.createOrder();
						}
				      })
					 
				    }
				    
				  }
				})
			},
			// 创建订单
			createOrder() {
				if(!this.choiceIndex) {
					uni.showModal({
						showCancel: false,
						title: "提示",
						content: "请选择取货方式"
					})
					return
				}
				if(this.orderId) {
					this.payment()
					return
				}
				var goods_param = []
				for (var i = 0; i < this.shoppCart.length; i++) {
					let data = {
						goods_id: this.shoppCart[i].id,
						count: this.shoppCart[i].number
					}
					goods_param.push(data)
				}
				var path = '/xyb/supermarket/order/create';
				var data = {
					goods_param: JSON.stringify(goods_param),
					delivery: this.choiceIndex, // 1商品自提 2商品代取
					remarks: this.remarks
				};
				ikz.post(path, data, res => {
					console.log("创建订单", res)
					if (res.data.code) {
						this.orderId = res.data.data.id
						this.orderNo = res.data.data.order_no
						let carts = uni.getStorageSync(this.shoppingCartStorageName)
						for (let i in carts) {
							if (carts[i].store_id == this.storeData.store_id) {
								carts.splice(i, 1)
								break;
							}
						}
						uni.setStorageSync(this.shoppingCartStorageName,carts)
						this.payment()
					} else {
						uni.showModal({
							title: '提示',
							content: res.data.msg,
							showCancel: false,
							success: function(res) {}
						});
					}
				})
			},
			// 调起小程序微信支付 
			payment() {
				uni.showLoading({
					mask: true,
					title: '正在请求支付...'
				})
				var path = '/xyb/supermarket/order/wx_minapp_pay';
				var data = {
					order_no: this.orderNo,
				};
				ikz.post(path, data, res => {
					console.log("调起小程序微信支付 ", res)
					uni.hideLoading()
					if (res.data.code == 1) {
						wx.requestPayment({
							timeStamp: res.data.data.timeStamp,
							nonceStr: res.data.data.nonceStr,
							package: res.data.data.package,
							signType: res.data.data.signType,
							paySign: res.data.data.paySign,
							success: res => {
								console.log('success', res);
								if (res.errMsg == "requestPayment:ok") {
									uni.showToast({
										title: '支付成功',
										duration: 2000,
										icon: 'success'
									})
									uni.redirectTo({
										url: "/pages/Component/supermarket/Program/store/success?id="+this.orderId+"&type="+this.choiceIndex+"&address="+this.storeData.address
									})
								}
							},
							fail: res => {
								console.log('fail', res);
								uni.showModal({
									title: "提示",
									showCancel: false,
									content: "订单已创建，请及时进行支付"
								})
							},
							complete: res => {
								console.log('complete', res);
							}
						})
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
					}
				})
			},
		}
	}
</script>

<style lang="scss">
	page {
		background: #F6F7FB;
	}

	.container {
		padding: 29rpx 29rpx 100px;

		.selected-all {
			display: flex;
			flex-direction: column;
			justify-content: center;
			width: 100%;
			background: #FFFFFF;
			border-radius: 9rpx;
			
			.drop-down-box {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 25rpx 29rpx;
				
				.dropdown-content {
					font-weight: 600;
					font-size: 29rpx;
					line-height: 40rpx;
					color: #FB7A26;
				}
				
				.dropdown-icon {
					width: 35rpx;
					height: 35rpx;
					
					&.select {
						transform: rotate(90deg);
					}
				}
			}
			
			.dialog-view {
				display: flex;
				flex-direction: column;
				justify-content: center;
				
				.dialog-title {
					font-size: 29rpx;
					border-top: 1rpx solid rgba(0, 0, 0, 0.1);
					padding: 20rpx 29rpx;
				}
			}
		}

		.store-list {
			background: #FFFFFF;
			border-radius: 9rpx;
			padding: 29rpx;
			margin-top: 20rpx;

			.title {
				margin-bottom: 29rpx;
				padding-bottom: 29rpx;
				border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);
				font-weight: 600;
				font-size: 29rpx;
				line-height: 40rpx;
				color: #333333;
			}

			.column {
				margin-bottom: 29rpx;
				display: flex;

				.left {
					width: 102rpx;
					height: 102rpx;
					border-radius: 9rpx;
				}

				.center {
					flex: 1;
					margin: 0 29rpx;
					display: flex;
					flex-wrap: wrap;
					align-content: space-between;

					.name {
						width: 100%;
						font-weight: 600;
						font-size: 26rpx;
						line-height: 29rpx;
						color: #333333;
						display: -webkit-box;
						-webkit-box-orient: vertical;
						overflow: hidden;
						-webkit-line-clamp: 2;
					}

					.num {
						width: 100%;
						font-weight: 400;
						font-size: 22rpx;
						line-height: 29rpx;
						color: #979797;
					}
				}

				.right {
					font-weight: 600;
					font-size: 33rpx;
					line-height: 29rpx;
					color: #333333;

					text {
						font-size: 22rpx;
					}
				}
			}

			.price-total {
				display: flex;
				justify-content: space-between;
				align-items: center;
				border-top: 1px solid rgba(0, 0, 0, 0.1);
				padding-top: 29rpx;

				.tag {
					font-weight: 400;
					font-size: 25rpx;
					line-height: 29rpx;
				}

				.price {
					font-weight: 600;
					font-size: 33rpx;
					line-height: 29rpx;
					color: #333333;

					text {
						font-size: 22rpx;
					}
				}
			}
		}

		.remarks {
			background: #FFFFFF;
			border-radius: 9rpx;
			padding: 29rpx;
			margin-top: 20rpx;

			.title {
				font-weight: 400;
				font-size: 25rpx;
				line-height: 29rpx;
			}

			textarea {
				margin-top: 22rpx;
				width: 100%;
				min-height: 180rpx;
				background: #F9F9F9;
				border-radius: 9rpx;
				padding: 22rpx 29rpx;
				font-size: 22rpx;
				box-sizing: border-box;
			}
		}

		.btn-box {
			position: fixed;
			z-index: 999;
			display: flex;
			bottom: 15px;
			justify-content: center;
			align-items: center;
			margin: 0;
			height: 50px;
			width: calc(100% - 32px);

			&-left {
				height: 100%;
				flex: auto;
				display: flex;
				justify-content: flex-start;
				align-self: center;
				align-items: center;
				background: #222222;
				border-top-left-radius: 100upx;
				border-bottom-left-radius: 100upx;
				padding-left: 17rpx;

				.priceBox {
					flex: auto;
					margin-left: 22rpx;

					.hx-color-white {
						font-weight: 600;
						font-size: 33rpx;
						line-height: 29rpx;
						color: #fff;

						text {
							font-size: 22rpx;
						}
					}
				}

			}

			&-right {
				width: 170rpx;
				height: 100%;
				position: relative;
				display: flex;
				justify-content: flex-start;
				align-self: center;
				align-items: center;

				.jiesuan {
					width: 100%;
					height: 100%;
					font-size: 28upx;
					border-top-right-radius: 100upx;
					border-bottom-right-radius: 100upx;
					text-align: center;
					display: flex;
					justify-content: center;
					align-self: center;
					align-items: center;
					background: linear-gradient(45deg, #FFEB3B, #FFC107);
					font-weight: bold;
				}
			}
		}
	}
</style>
